var zoom = 1.0, xzer = 0.0, yzer = 0.0, height = 0.0, width = 0.0
var image = new Image()
var openFile = function() {
	Dackage.$('.file').click()
}
var showImage= function(image, height, width) {
	var canvas = Dackage.$('.app')
	var ctx = canvas.getContext('2d')
	ctx.clearRect(0, 0, canvas.width, canvas.height)
	ctx.drawImage(image, xzer, yzer, width * zoom, height * zoom)
}
var handleFile = function() {
	var fileList = this.files
	var canvas = Dackage.$('.app')
	image._listener('load', function(e){
		if (image.height > image.width) {
			width = canvas.width * (image.width / image.height)
			height = canvas.height
		} else if (image.height == image.width) {
			width = canvas.width
			height = canvas.height
		} else {
			width = canvas.width
			height = canvas.height * (image.height / image.width)
		}
		showImage(image, height, width)
		Dackage.$('.totop')._listener('click', moving(10, 'y', image.height))
		Dackage.$('.tobottom')._listener('click', moving(-10, 'y', image.height))
		Dackage.$('.toleft')._listener('click', moving(10, 'x', image.width))
		Dackage.$('.toright')._listener('click', moving(-10, 'x', image.width))

	})
	var reader = new FileReader()
	reader.addEventListener('load', function(e){
		var result = e.target.result
		image.src = result
	})
	reader.readAsDataURL(fileList[0])
}
var zoomer = function(value) {
	return function() {
		var canvas = Dackage.$('.app')
		zoom += value
		if (zoom <= 0.1) {
			zoom = 0.1
		}
		yzer -= canvas.height / 2 * value
		xzer -= canvas.width / 2 * value
		showImage(image, height, width)
	}
}
var moving = function(value, key, max) {
	if (key == 'x') {
		return function() {
			xzer += value
			if (xzer < -max) {
				xzer = -max
			} else if (xzer > max) {
				xzer = max
			}
			showImage(image, height, width)
		}
	}
	else if (key == 'y') {
		return function() {
			yzer += value
			if (yzer < -max) {
				yzer = -max
			} else if (yzer > max) {
				yzer = max
			}
			showImage(image, height, width)
		}
	}
}
var main = function() {
	var canvas = Dackage.$('.app')
	var openButton = Dackage.$('.open')
	var fileInput = Dackage.$('.file')
	var increaseButton = Dackage.$('.increase')
	var reduceButton = Dackage.$('.reduce')
	Dackage.$('.app').height = Dackage.$('.app').width
	openButton._listener('click', openFile)
	fileInput._listener('change', handleFile)
	increaseButton._listener('click', zoomer(0.1))
	reduceButton._listener('click', zoomer(-0.1))
}
window.addEventListener('load', main)